<?php
namespace app\article\controller;


use app\admin\model\AppConfig;
use app\ApiRest;
use app\article\model\ArticleClassifyModel;
use app\article\model\ArticleConfigModel;
use app\article\model\ArticleContentModel;
use app\article\model\ArticleDateModel;
use app\article\model\ArticleModel;
use app\article\model\ArticleRecordModel;
use app\base\model\CardTimeline;
use app\base\model\CardUser;
use app\base\model\CardUserInfo;
use app\card\model\CardCount;
use app\card\model\Job;
use app\card\model\User;
use app\card\model\UserInfo;
use app\Common\ArticleFromUrl;
use app\marketing\model\MarketingArticleV2;
use app\marketing\model\MarketingDate;
use app\marketing\model\MarketingRecord;
use app\radar\model\RadarCount;
use app\shop\model\IndexUserInfo;
use app\dynamic\model\CardTimeline as TimelineTimeline;
use think\App;
use think\facade\Db;
use think\facade\Cache;
use app\Common\model\LongbingCardCount;
use app\Common\Upload;
class WxAppArticle extends ApiRest
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function listAll()
    {
        $param = $this->_param;
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        $filter = [
            ['uniacid', '=', $this->_uniacid],
            ['user_id', '=', 0],
            ['status', '=', 1],
        ];

        if (isset($param['classify_id']) && $param['classify_id'] > 0)
        {
            array_push($filter, ['classify_id', '=', $param['classify_id']]);
        }
        $model = new ArticleModel();
        $page_config['total'] = $model->countByFilter($filter);
        $rsts = $model->where($filter)
            ->field('id, title, cover, share, view, classify_id,share_self ')
            ->order(['top' => 'desc', 'id' => 'desc'])
            ->page($page_config['page'], $page_config['page_count'])
            ->select()->toArray();


        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $result['data'] = $rsts;

        if ($result['data'])
        {
            $classifyModel = new ArticleClassifyModel();

            $classify = $classifyModel
                ->field('id, title')
                ->where(['uniacid' => $this->_uniacid])
                ->select()->toArray();

            foreach ($result['data'] as $index => $item) {
                foreach ($classify as $k => $v) {
                    if ($item['classify_id'] == $v['id'])
                    {
                        $result['data'][$index]['classify_title'] = $v['title'];
                    }
                }
            }
        }

        return $this->success($result);
    }

    public function getOne()
    {
        $uniacid = $this->_uniacid;
        $id = $this->_param['article_id'] ?? null;
        $to_uid = $this->_param['to_uid'] ?? null;
        $user_id = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? '';

        if (!$id || !$user_id)
        {
            return $this->error('id and user_id are required');
        }

        $user = Db::name('longbing_card_user')->where(['id' => $user_id])->find();

        if (!$user)
        {
            return $this->error('user not found');
        }

        $articleModel = new ArticleModel();

        $article = $articleModel->alias('a')
            ->field([
                'a.id', 'a.user_id', 'a.classify_id', 'a.title', 'a.cover', 'a.view', 'a.share', 'a.create_time',
                'b.content', 'a.content as a_content', 'a.status'
            ])
            ->join('lb_marketing_article_content b', 'a.content = b.id', 'left')
            ->where(['a.id' => $id, 'a.status' => 1])
            ->find();

        if (!$article)
        {
            return $this->error('article is not exists or deleted');
        }
        if ($article['user_id'] == 0)
        {
            $article->view = $article->view + 1;
            $article->save();
        }
        $article['record_id'] = 0;

        //  是否是自己的文章
        if ($user_id != $article['user_id'] && $article['user_id'] != 0)
        {
            $article->view = $article->view + 1;
//            unset($article['record_id']);
//            unset($article['my_article_id']);
            $article->save();
            $recordModel = new ArticleRecordModel();

            $count = $recordModel
                ->where([
                    'article_id' => $id,
                    'user_id' => $user_id,
                    'staff_id' => $to_uid,
                    'type' => 1,
                    'uniacid' => $uniacid,
                ])
                ->count();

            $recordModel->article_id = $id;
            $recordModel->user_id = $user_id;
            $recordModel->staff_id = $to_uid;
            $recordModel->type = 1;
            $recordModel->uniacid = $uniacid;
            $recordModel->number = $count + 1;
            $recordModel->save();
            $article['record_id'] = $recordModel->id;

//            $countModel = new LongbingCardCount();
//            $countModel->user_id = $user_id;
//            $countModel->to_uid = $to_uid;
//            $countModel->sign = 'view';
//            $countModel->type = 12;
//            $countModel->uniacid = $uniacid;
//            $countModel->target = $id;
//            $countModel->save();
//
//            //发送雷达通知
//            if (!empty($countModel->id))
//            {
//                $push_data = array(
//                    'action' => 'SendWxServiceNotice',
//                    'event' => 'SendWxServiceNotice',
//                    'count_id' => $countModel->id
//                );
//                publisher(json_encode($push_data, true), 5000);
//            }
//
        }


        $article['my_article_id'] = $article['id'];
        $article['need_confirm'] = 0;

        if (($article['user_id'] == 0 || $user_id != $article['user_id']) && $user['is_staff'] == 1)
        {
            //  检查我有没有这篇文章
            $my_article = $articleModel
                ->where([
                    'user_id' => $user_id,
                    'content' => $article['a_content'],
                    'uniacid' => $uniacid
                ])
                ->find();

            if ($my_article)
            {
                if ($my_article['status'] == -1)
                {
                    $article['need_confirm'] = 1;
                }
                $article['my_article_id'] = $my_article->id;
            } else {
                $article['need_confirm'] = 1;
                $articleModel2 = new ArticleModel();
                $articleModel2->user_id = $user_id;
                $articleModel2->content = $article['a_content'];
                $articleModel2->uniacid = $uniacid;
                $articleModel2->classify_id = $article['classify_id'];
                $articleModel2->title = $article['title'];
                $articleModel2->cover = $article['cover'];
                $articleModel2->source_id = $article['id'];
                $articleModel2->status = -1;

                $articleModel2->save();
                $article['my_article_id'] = $articleModel2->id;
            }
        }

        if ($user_id == $article['user_id'] || $user['is_staff'] != 1)
        {
            $article['my_article_id'] = $article['id'];
        }


        $article['content']  = getimgs($article['content']);
        $article['content1'] = getimgsV2($article['content']);
        $article['is_staff'] = $user['is_staff'];
        $article['is_huoke_permission'] = 1;

        $article['time'] = date('Y-m-d H:i:s', $article['create_time']);
        $article['create_time2'] = lb_friendly_date($article['create_time'], 'full');

        if ($to_uid)
        {
            $key = 'longbing_user_card_info_' . $to_uid;

            $value = getCache($key, $this->_uniacid);
            if ($value && false)
            {
                $value['from_cache'] = 1;
                $article['cardInfo'] = $value;
            } else {
                $cardInfo = UserInfo::where([['fans_id', '=', $to_uid]])
                    ->find();
                if ($cardInfo)
                {
                    $cardInfo = $cardInfo->toArray();

                    $job = Job::where([['id', '=', $cardInfo['job_id']]])
                        ->find();

                    if (!$job)
                    {
                        $cardInfo['job_name'] = '未设置职位';
                    } else {
                        $job = $job->toArray();
                        $cardInfo['job_name'] = $job['name'];
                    }
                    $cardInfo = transImages($cardInfo, ['images'], ',');
                    $cardInfo = transImagesOne($cardInfo, ['avatar', 'voice', 'my_url', 'my_video', 'my_video_cover', 'bg',
                            'vr_cover', 'vr_path']
                    );

                    if (isset($cardInfo['my_video']) && is_array($cardInfo['my_video']) && !empty($cardInfo['my_video']))
                    {

                        $cardInfo['my_video_vid'] = lbGetTencentVideo($cardInfo['my_video'][0]);
                    }

                    $modelCount = new RadarCount();
                    list($viewCount, $thumbCount) = $modelCount->RadarNumber($to_uid,$this->_uniacid);
                    $cardInfo['viewCount'] = $viewCount;
                    $cardInfo['thumbCount'] = $thumbCount;

                    $article['cardInfo'] = $cardInfo;
                    setCache($key, $cardInfo, 1800, $this->_uniacid);
                }
            }
        }

        $field = 'id, title, cover, update_time, classify_id';

        $order = ['top'=>'desc','view' => 'desc', 'update_time' => 'desc', 'id' => 'desc'];

        $where = [
            ['user_id', '=', $to_uid],
            ['uniacid', '=', $this->_uniacid],
            ['status', '=', 1],
            ['id', '<>', $id],
        ];

        //  列表
        $hot_list = $articleModel
            ->field($field)
            ->order($order)
            ->where($where)
            ->limit(5)
            ->select()->toArray();


        if ($hot_list)
        {
            $classifyModel = new ArticleClassifyModel();

            $classify = $classifyModel
                ->field('id, title')
                ->where(['uniacid' => $this->_uniacid])
                ->select()->toArray();

            foreach ($hot_list as $index => $item) {
                $hot_list[$index]['time'] = lb_friendly_date($item['update_time']);

                foreach ($classify as $k => $v) {
                    if ($item['classify_id'] == $v['id'])
                    {
                        $hot_list[$index]['classify_title'] = $v['title'];
                    }
                }
            }
        }

        $article['hot_list'] = $hot_list;

        //生成文章二维码
        $articleQrData = [
            'staff_id' => $to_uid,
            'pid' => $user_id,
            'id' => $id,
            'type' => 6
        ];
        $articleQr = Cache::get($id.'-'.$to_uid.'-'.$user_id."-6-article_qr");
        if(empty($articleQr)||!is_file($articleQr)){
            $data = longbingCreateWxCode($this->_uniacid,$articleQrData,'article/pages/detail');
            if(isset($data['qr_path'])) $data = transImagesOne($data ,['qr_path'] ,$this->_uniacid);
            $articleQr = $data['qr_path'];
            Cache::set($id.'-'.$to_uid.'-'.$user_id."-6-article_qr",$data['qr_path']);
        }
        $article['articleQr'] = $articleQr;


        // return $this->success($article);

        //  返回
        // @fastcgi_finish_request();

        //  记录今日获客文章
        if ($user_id != $article['user_id'] && $article['user_id'] != 0) {

            $this->setClients($to_uid, $user_id, $id, $recordModel->id, $uniacid);
        }

        $config = longbingGetArticleConfig($this->_uniacid);

        $article['look_card'] = $config['look_card'];

        return $this->success($article);
    }

    public function importArticle()
    {
        global $_W;

        $uniacid = $this->_uniacid;
        $url = $this->_param['url'] ?? "";
        $url = trim($url);
        $classify_id = $this->_param['classify_id'] ?? null;
        if (!$classify_id || !$url)
        {
            return $this->error('请传入正确的参数');
        }
        $user_id = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;

//        $checkArticle = $this->checkArticle($uniacid, 0, $user_id);
        $checkArticle = lbSingleCheckArticleV2($uniacid, $user_id);

        if ($checkArticle !== 1)
        {
            $msg = '没有使用获客文章的权限, 请联系管理员';
            return $this->error($msg);
        }

//        Db::startTrans();
        //  检查连接是否正确
        try {
            file_get_contents($url);
        } catch (\Exception $e) {
            return $this->error('please check url');
        }

        $articleModel = new ArticleModel();
        $contentModel = new ArticleContentModel();


        $articleFromUrl = new ArticleFromUrl($url);
        $articleInfo = $articleFromUrl->getArticle();

        if (!$articleInfo['content'])
        {
            return $this->success('fail');
        }


        //  检查这篇文章是否导入过了
        $check = $contentModel->where(['url' => $url])->find();
        if (!$check)
        {
            $contentModel->cover = '';
            $contentModel->content = $articleInfo['content'];
            $contentModel->url = $url;
            $contentModel->status = 1;
            $contentModel->uniacid = $uniacid;
            $contentModel->save();
            $content_id = $contentModel->id;
        }

        $articleModel->user_id = $user_id;
        $articleModel->classify_id = $classify_id;
        $articleModel->title = $articleInfo['title'];

        $articleModel->status = 1;
        $articleModel->uniacid = $uniacid;



        if ($check)
        {

            $content_id = $check->id;
            $articleModel->content = $content_id;
            $articleModel->cover = $check->cover;

            $articleModel->save();
            return $this->success('import success!');
        }



        $oss_config = longbingGetOssConfig($uniacid);


        $articleModel->content = $content_id;
        $articleModel->cover = '';
        $res = $articleModel->save();

        if ($res)
        {
            $id = $articleModel->id;

            echo json_encode(['code' => 200, 'sign' => null, 'data' => ['id' => $id]]);

             //直接输出
            if (function_exists('fastcgi_finish_request')) {
                @fastcgi_finish_request();
            }

            $articleInfo['content'] = html_entity_decode($articleInfo['content']);



/*            $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';//匹配img标签的正则表达式*/
            $preg = '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';//匹配img标签的正则表达式

            preg_match_all($preg, $articleInfo['content'], $allImg);//这里匹配所有的img
            $allImg = $allImg[0];
            try {
                //  转存图片
                if (!is_dir(FILE_UPLOAD_PATH . "images")) {
                    mkdir(FILE_UPLOAD_PATH . "images");
                }
                if (!is_dir(FILE_UPLOAD_PATH . "images/a_qr")) {
                    mkdir(FILE_UPLOAD_PATH . "images/a_qr");
                }
                if (!is_dir(FILE_UPLOAD_PATH  . "images/article/")) {
                    mkdir(FILE_UPLOAD_PATH  . "images/article/");
                }
          		if (!is_dir(FILE_UPLOAD_PATH  . "images/article/" . $uniacid .'/')) {
                    mkdir(FILE_UPLOAD_PATH  . "images/article/" . $uniacid .'/');
                }
				if (!is_dir(FILE_UPLOAD_PATH  . "images/article/" . $uniacid .'/' . date('y') . '/')) {
                    mkdir(FILE_UPLOAD_PATH  . "images/article/" . $uniacid .'/' . date('y') . '/');
                }
				if (!is_dir(FILE_UPLOAD_PATH  . "images/article/" . $uniacid .'/' . date('y') . '/' . date('m')  . '/')) {
                    mkdir(FILE_UPLOAD_PATH  . "images/article/" . $uniacid .'/' . date('y') . '/' . date('m') . '/');
                }
                //$destination_folder = FILE_UPLOAD_PATH . 'images/article/';
				$destination_folder = 'images/article/' . $uniacid  . '/' . date('y') . '/' . date('m') . '/';
                //@load()->func('file');

                foreach ($allImg as $index2 => $item2) {

                    if(strpos($item2,'qpic') !== false){
                        $ftype = '.png';
                        $res = getimagesize($item2);
                        if (isset($res['mime']))
                        {
                            if (strpos($res['mime'], 'gif'))
                            {
                                $ftype = '.gif';
                            }
                        }
                        //生成名字
                        $path = $destination_folder . uuid() . $ftype;
                        //获取文件
                        $file = file_get_contents($item2);
                        $file = file_put_contents(FILE_UPLOAD_PATH  . $path , $file);
                        $file_upload_model = new Upload($uniacid);
                        $check = $file_upload_model->uploadFile($path);
                        $path  = !empty($oss_config['open_oss'])&&$oss_config['open_oss']==1? $oss_config['aliyun_base_dir'].'/'.$path:$path;
                        $allImg[$index2] = $path;
                        $allImg = transImagesOne($allImg ,[$index2] ,$uniacid);
//                        dump($allImg[$index2]);exit;
                        $articleInfo['content'] = str_replace($item2, $allImg[$index2], $articleInfo['content']);
                    }
                }
            } catch (\Exception $exception) {

            }

            foreach ($allImg as $index => $item) {

                $size = @getimagesize($item);

                if ($size[0] > 100 && $size[1] > 100) {
                    $item_arr = explode('.', $item);

                    if ($item_arr[count($item_arr) - 1] == 'gif') {
                        continue;
                    }
                    $articleInfo['cover'] = $allImg[$index];
                    break;
                }
            }


            //  替换旧的内容
            $contentModel->where('id', $content_id)
                ->update(['cover' => $articleInfo['cover'], 'content' => $articleInfo['content']]);

            $articleModel->where('content', $content_id)
                ->update(['cover' => $articleInfo['cover']]);

            //  判断是否开启自动同步
            $configModel = new ArticleConfigModel();
            $config = $configModel->where(['uniacid' => $uniacid])->find();
            if ($config && $config['check_switch']==1)
            {

                $articleModel = new ArticleModel();
                $articleModel->user_id = 0;
                $articleModel->source_id = $id;
                $articleModel->classify_id = $classify_id;
                $articleModel->title = $articleInfo['title'];
                $articleModel->cover = $articleInfo['cover'];
                $articleModel->content = $content_id;
                $articleModel->uniacid = $uniacid;

                $articleModel->save();
            }
//            Db::commit();
            // return $this->success(['id' => $id]);

        }

        return $this->error('fail');
    }

    public function logicDel()
    {
        $id = $this->_param['article_id'];
        $model = new ArticleModel();
        $rst = $model->updateByfilter(['id' => $id, 'user_id' => $this->_user_id], ['status' => -1]);
        return $this->success($rst);
    }

    /**
     * @Purpose: 上报分享文章
     *
     * @Param: int $id 文章id
     * @Param: int $to_uid 员工id
     * @Param: int $type 记录类型: 1: 分享  2：保存海报
     * @Param: int $record_id 记录id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function shareRecord()
    {
        $uniacid = $this->_uniacid;
        $id = $this->request->param('id') ?? null;
        $to_uid = $this->request->param('to_uid') ?? null;
        $type_get = $this->request->param('type') ?? 1;
        $record_id = $this->request->param('record_id') ?? null;

        if ($record_id)
        {
            $record = ArticleRecordModel::where('id', '=', $record_id);
            if (!$record) {
                $msg = '没有找到记录';
                return $this->error($msg);
            }
            $record->length = $record->length + time() - $record->update_time;
            $record->save();
            return $this->success('suc');
        }

        $user_id = $this->_user_id ?? $this->_input['onlyForTestUserId'] ?? null;

        if (!$id || !$user_id)
        {
            return $this->error('param is required');
        }

        $userModel = new User();
        $user = $userModel->where(['id' => $user_id])->find();

        if (!$user)
        {
            return $this->error('this record not found');
        }

        $articleModel = new ArticleModel();

        $article = $articleModel
            ->where(['id' => $id, 'status' => 1])
            ->find();

        if (!$article)
        {
            return $this->error('this record not found');
        }

        //  判断是否做记录
        if ($user_id != $article['user_id'] && $article['user_id'] != 0)
        {

            $recordModel = new ArticleRecordModel();
            $type = 2;
            $article->share_other += 1;
            if ($type_get == 2)
            {
                $type = 5; //分享海报
                $article->poster = $article->poster + 1;
                $article->save();
            } else {
                $article->share = $article->share + 1;
                $article->save();
            }
            $count = $recordModel
                ->where([
                    'article_id' => $id,
                    'user_id' => $user_id,
                    'staff_id' => $to_uid,
                    'type' => $type,
                    'uniacid' => $uniacid,
                ])
                ->count();

            $recordModel->article_id = $id;
            $recordModel->user_id = $user_id;
            $recordModel->staff_id = $to_uid;
            $recordModel->type = $type;
            $recordModel->number = $count + 1;

            $recordModel->uniacid = $uniacid;
            $recordModel->save();


//            $countModel = new CardCount();
//            $countModel->user_id = $user_id;
//            $countModel->to_uid = $to_uid;
//            $countModel->sign = 'view';
//            $countModel->type = 13;
//            if ($type_get == 2) {
//                $countModel->type = 14; //分享海报
//            }
//            $countModel->uniacid = $uniacid;
//            $countModel->target = $id;
//            $countModel->save();


//            //发送雷达通知
//            if (!empty($countModel->id)) {
//                $push_data = array(
//                    'action' => 'SendWxServiceNotice',
//                    'event' => 'SendWxServiceNotice',
//                    'count_id' => $countModel->id
//                );
//                publisher(json_encode($push_data, true), 5000);
//            }

        } else {
            $article->share_self += 1;
            $article->save();
        }

        return $this->success('suc');

    }

    public function listMyArticle()
    {
        global $_W;

        $param = $this->_param;
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        $to_uid = $param['to_uid'] ?? $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        $filter = [
            ['uniacid', '=', $this->_uniacid],
            ['status', '=', 1],
            ['user_id', '=', $to_uid]
        ];

        if (isset($param['classify_id']) && $param['classify_id'] > 0)
        {
            array_push($filter, ['classify_id', '=', $param['classify_id']]);
        }
        $model = new ArticleModel();
        $page_config['total'] = $model->countByFilter($filter);
        $rsts = $model->where($filter)
            ->field('id, title, cover, share, view, poster,classify_id, create_time, status')
            ->order(['top' => 'desc', 'create_time' => 'desc'])
            ->page($page_config['page'], $page_config['page_count'])
            ->select()->toArray();


        $rsts = transImagesOne($rsts, ['cover']);
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $result['data'] = $rsts;

        if ($result['data'])
        {
            $classifyModel = new ArticleClassifyModel();
            $classify = $classifyModel
                ->field('id, title')
                ->where(['uniacid' => $this->_uniacid])
                ->select()->toArray();

            foreach ($result['data'] as $index => $item) {
                $result['data'][$index]['create_time'] = lb_friendly_date($item['create_time']);

                foreach ($classify as $k => $v) {
                    if ($item['classify_id'] == $v['id'])
                    {
                        $result['data'][$index]['classify_title'] = $v['title'];
                    }
                }
            }
        }

        $recordModel = new ArticleRecordModel();
        $total_view = $recordModel->where(['staff_id' => $to_uid, 'type' => 1])->count();

        $date = date('Y-m-d');
        $time = strtotime($date . ' 00:00:00');
        $today_view = $recordModel
            ->where([
                ['staff_id', '=', $to_uid],
                ['type', '=', 1],
                ['create_time', '>', $time]
            ])
            ->count();
        $result['total_view'] = $total_view;
        $result['today_view'] = $today_view;


        $whereList = array(
            'uniacid' => $this->_uniacid,
        );
//        $subQuery = Db::table('ims_lb_marketing_record')
//            ->where($whereList)
//            ->group('user_id')
//            ->buildSql();
//
//        $rank = Db::table($subQuery . ' a')
//            ->field(array(
//                "count(a.user_id)" => "countUser",
//                'b.nickName', 'b.avatarUrl', 'c.name', 'c.avatar', 'b.id'
//            ))
//            ->join('ims_longbing_card_user b', 'b.id = a.staff_id', 'left')
//            ->join('ims_longbing_card_user_info c', 'c.fans_id = b.id', 'left')
//            ->order(['countUser' => 'desc'])
//            ->group('a.staff_id')
//            ->limit(3)
//            ->select()->toArray();
//
//        if (!empty($rank)) {
//            foreach ($rank as $index => $item) {
////                $rank[ $index ][ 'avatar' ] = $this->lb_src_trans( $item[ 'avatar' ], false, $_W );
//            }
//        }

        $subQuery = Db::name('lb_marketing_article_date')
            ->where($whereList)
            ->field(['sum(count) as countUser', 'user_id'])
            ->group('user_id')
            ->buildSql();

        //  排名列表
        $rank_list = Db::table($subQuery . ' a')
            ->field([
                'a.countUser', 'a.user_id' => 'id',
                'b.name', 'b.avatar',
            ])
            ->where([
                'c.status' => 1,
                'b.is_staff' => 1
            ])
            ->join('longbing_card_user_info b', 'b.fans_id = a.user_id', 'left')
            ->join('lb_marketing_article_v2 c', 'c.user_id = a.user_id', 'left')
            ->group('a.user_id')
            ->order(['countUser' => 'desc'])
            ->limit(3)->select()->toArray();

        $rank_list = transImagesOne($rank_list, ['avatar']);
        $result['rank'] = $rank_list;

        return $this->success($result);
    }

    public function syncArticle()
    {
        $timelineModel = new TimelineTimeline();

//        do {
//            if (!defined(LONGBING_AUTH_TIMELINE)) {
//                return $this->error('发布动态已达上限');
//            }
//
//            if (LONGBING_AUTH_TIMELINE == 0) {
//                break;
//            }
//            $count = $timelineModel->where(['uniacid'=>$this->_uniacid])->count();
//            if($count>=LONGBING_AUTH_TIMELINE){
//                return $this->error('发布动态已达上限');
//            }
//        } while(false);

        $input   = $this->_param;

        $uniacid = $this->_uniacid;

        $id = $this->_param['article_id'];

        $user_id = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;

        $articleModel = new ArticleModel();
        $res = $articleModel->where(['id' => $id])->find();

        if (!$res)
        {
            return $this->error('article not found');
        }

        if ($res['user_id'] != $user_id)
        {
            $checkInfo = $articleModel
                ->where([
                    'user_id' => $user_id,
                    'source_id' => $id
                ])
                ->find();
            if ($checkInfo['status'] == -1)
            {
                $checkInfo->satus = 1;
                $checkInfo->save();
            }
            if (!$checkInfo)
            {
                $new = json_encode($res);
                $new = json_decode($new, true);
                unset($new['id']);
                unset($new['create_time']);
                unset($new['update_time']);
                $new['user_id'] = $user_id;
                $new['view'] = 0;
                $new['share'] = 0;
                $new['source_id'] = $id;
                $articleModel = new ArticleModel();
                $articleModel->data($new);
                $res = $articleModel->save();
                if ($res)
                {
                    $res = $articleModel->where(['id' => $articleModel->id])->find();
                }
            }

        }

        $timelineModel->user_id = $user_id;
        $timelineModel->title = $res['title'];
        $timelineModel->cover = $res['cover'];
        $timelineModel->content = $res['content'];
        $timelineModel->uniacid = $uniacid;
        $timelineModel->status = 1;
        $timelineModel->type = 3;

        $timelineModel->article_id = $res['id'];

        $timelineModel->cate_id = !empty($input['cate_id'])?$input['cate_id']:0;

        $result = $timelineModel->save();

        if ($result)
        {
            return $this->success(['id' => $timelineModel->id]);
        }

        return $this->error('sync fail');
    }


    public function rankClient()
    {
        global $_W;
        $uniacid = $this->_uniacid;
        //  根据自定义的条件获取参数
        $page = $this->_param['page'] ?? 1;
        $type = $this->_param['type'] ?? 0;


        $time = date('Y-m-d', strtotime('-29 days'));
        $start_date = $time;
        $time = $time . ' 00:00:00';
        $time_start = strtotime($time);

        $where = [
            ['uniacid', '=', $uniacid],
        ];
        $daysArr = array();

        //  @Param: int      $type     查询列表类型 0 => 所有的数据 1 => 昨天 2 => 近7天 3 => 近15天
        switch ($type) {
            case 0:
                $daysArr = $this->getDaysArr(30);
//                array_push($where, ['create_time', '>', $time_start]);
                break;
            case 1:
                $time = date('Y-m-d', strtotime('-1 days'));
                $start_date = $time;
                $time_start = $time . ' 00:00:00';
                $time_end = $time . ' 23:59:59';
                $time_start = strtotime($time_start);
                $time_end = strtotime($time_end);
                array_push($where, ['create_time', 'between', [$time_start, $time_end]]);
                $tmp = date('m/d', strtotime('-1 days'));
                $daysArr[$tmp] = array('count' => 0, 'date' => $tmp);
                break;
            case 2:
                $time = date('Y-m-d', strtotime('-6 days'));
                $start_date = $time;
                $time = $time . ' 00:00:00';
                $time_start = strtotime($time);
                array_push($where, ['create_time', '>', $time_start]);
                $daysArr = $this->getDaysArr(7);
                break;
            case 3:
                $time = date('Y-m-d', strtotime('-14 days'));
                $start_date = $time;
                $time = $time . ' 00:00:00';
                $time_start = strtotime($time);
                array_push($where, ['create_time', '>', $time_start]);
                $daysArr = $this->getDaysArr(15);
                break;
        }

        $articleDateModel = new ArticleDateModel();
        $list = $articleDateModel->where($where)->select()->toArray();

        if ($list)
        {
            foreach ($list as $index => $item) {
                $tmp_date = $item['month_day'];
                foreach ($daysArr as $key => $val) {
                    if ($key == $tmp_date)
                    {
                        $daysArr[$key]['count'] += $item['count'];
                    }
                }
            }
        }


        $subQuery = Db::name('lb_marketing_article_date')
            ->where($where)
            ->field(['sum(count) as count', 'user_id'])
            ->group('user_id')
            ->buildSql();

        //  排名列表
        $rank_list = Db::table($subQuery . ' a')
            ->field([
                'a.count', 'a.user_id',
                'b.name', 'b.avatar',
                'count(c.id) as article_count',
                'd.name as job_name'
            ])
            ->where([
                'c.status' => 1,
                'b.is_staff' => 1
            ])
            ->join('longbing_card_user_info b', 'b.fans_id = a.user_id', 'left')
            ->join('lb_marketing_article_v2 c', 'c.user_id = a.user_id', 'left')
            ->join('longbing_card_job d', 'd.id = b.job_id', 'left')
            ->group('a.user_id')
            ->order(['count' => 'desc'])
            ->paginate(20, false, ['page' => $page])->toArray();


        $rank_list['client_total'] = 0;
        if (isset($rank_list['data']) && !empty($rank_list['data']))
        {
            $tmp_ids = array();
            foreach ($rank_list['data'] as $index => $item) {
                $rank_list['client_total'] += $item['count'];
//                $rank_list['data'][$index]['avatar'] = $this->lb_src_trans($item['avatar'], false, $_W);
                array_push($tmp_ids, $item['user_id']);
            }

        }

        $data = $rank_list;


        $msg = '请求成功';
        $data['msg'] = $msg;
        $data['daysArr'] = array_values($daysArr);
        $data['start_date'] = $start_date;


        return $this->success($data);
    }

    public function rankArticle()
    {
        $uniacid = $this->_uniacid;
        $page = $this->request->param('page');

        if (!$page) {
            $page = 1;
        }

        $data = ArticleModel::alias('a')
            ->where([
                'a.uniacid' => $uniacid,
                'a.user_id' => 0,
                'a.status' => 1,
            ])
            ->join('lb_marketing_classify b', 'b.id = a.classify_id', 'left')
            ->field([
                'a.id', 'a.title', 'a.cover', 'a.share', 'a.view', 'a.update_time', 'a.content',
                'b.title as classify_title'
            ])
            ->order(['view' => 'desc'])
            ->paginate(20, false, ['page' => $page])
            ->toArray();

        return $this->success($data);
    }

    public function confirmSync()
    {
        $id = $this->_param['article_id'];
        $model = new ArticleModel();
        $rst = $model->updateByfilter(['id' => $id], ['status' => 1]);
        return $this->success($rst);
    }

    /**
     * @Purpose: 文章浏览记录
     *
     * @Param: int      $article_id     文章id
     * @Param: int      $type     查询列表类型 0 => 浏览 1 => 转发 2 => 海报
     * @Param: int      $count     查询列表类型 0 => 所有的数据 1 => 7天的数据 2 => 今天的数据
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function viewRecord()
    {
        $uniacid = $this->_uniacid;
        //  获取当前用户id
        $uid = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;

        //  根据自定义的条件获取参数
        $article_id = $this->_param['article_id'] ?? null;
        $page = $this->_param['page'] ?? null;
        $count = $this->_param['count'] ?? 0;
        $type = $this->_param['type'] ?? 0;

        if (!$page) {
            $page = 1;
        }


        $where = [
            ['uniacid', '=', $uniacid],
            ['staff_id', '=', $uid],
        ];
        if ($article_id) {
//            $where['article_id'] = $article_id;
            array_push($where, ['article_id', '=', $article_id]);
        }
        switch ($type) {
            case 0:
                array_push($where, ['type', '=', 1]);
                break;
            case 1:
                array_push($where, ['type', '=', 2]);
                break;
            case 2:
                array_push($where, ['type', '=', 5]);
                break;
        }

        //  @Param: int      $count     查询列表类型 0 => 所有的数据 1 => 7天的数据 2 => 今天的数据
        if ($count == 1)
        {
            $time = date('Y-m-d', strtotime('-7 days'));
            $time = $time . ' 00:00:00';
            $time = strtotime($time);
            $where[] = ['update_time', '>', $time];
        }

        //  @Param: int      $count     查询列表类型 0 => 所有的数据 1 => 7天的数据 2 => 今天的数据
        if ($count == 2)
        {
            $time = date('Y-m-d');
            $time = $time . ' 00:00:00';
            $time = strtotime($time);
            $where[] = ['update_time', '>', $time];
        }

        $subQuery = Db::name('lb_marketing_record')
            ->where($where)
            ->order(['id' => 'desc'])
            ->buildSql();


        $list = Db::table($subQuery . ' a')
            ->order(['a.id' => 'desc'])
            //            ->where( $where )
            ->field(array(
                "count(a.id)" => "countId", "sum(a.length)" => "viewLength", "a.user_id",
                'b.nickName', 'b.avatarUrl', 'a.update_time'
            ))
            ->join('longbing_card_user b', 'b.id = a.user_id', 'left')
            ->group('user_id')
            ->paginate(20, false, ['page' => $page])
            ->toArray();

        if (isset($list['data']) && !empty($list['data']))
        {
            foreach ($list['data'] as $index => $item) {
                $tmp = $item['update_time'];
                $list['data'][$index]['update_time'] = lb_friendly_date($tmp);
                $list['data'][$index]['update_time1'] = date('Y-m-d', $tmp);
                $list['data'][$index]['update_time2'] = date('H:i', $tmp);
                $length = $item['viewLength'];
                if ($length < 60) {
                    $length_tmp = $length . '秒';
                } else if ($length < 3600) {
                    $length_tmp = floor($length / 60) . '分' . $length % 60 . '秒';
                } else {
                    $length_tmp = floor($length / 3600) . '小时' . floor($length % 3600 / 60) . '分' . $length % 60 . '秒';
                }
                $list['data'][$index]['viewLength'] = $length_tmp;
            }
        }

        $where = [
            ['article_id', '=', $article_id]
        ];
        if ($count)
        {
            $where[] = ['update_time', '>', $time];
        }
        $articleModel = new ArticleRecordModel();

        //  浏览次数
        $view_filter = $where;
        $view_filter[] = ['type', '=', 1];
        $view_count = $articleModel
            ->where($view_filter)
            ->count();

        //  转发次数
        $share_filter = $where;
        $share_filter[] = ['type', '=', 2];
        $share_count = $articleModel
            ->where($share_filter)
            ->count();

        //  海报次数
        $poster_filter = $where;
        $poster_filter[] = ['type', '=', 5];
        $poster_count = $articleModel
            ->where($poster_filter)
            ->count();


        $list['view_count'] = $view_count;
        $list['share_count'] = $share_count;
        $list['poster_count'] = $poster_count;


        return $this->success($list);
    }


    //获客排行榜--获客详情
    public function staffClientDetail()
    {
        global $_W;
        $uniacid = $this->_uniacid;

        //  根据自定义的条件获取参数
        $page = $this->_param['page'] ?? 1;

        $to_uid = $this->_param['to_uid'] ?? null;

        if (!$to_uid) {
            return $this->error('to_uid is required');
        }

        $info = UserInfo::alias('a')
            ->where([
                'a.fans_id' => $to_uid,
                'a.is_staff' => 1
            ])
            ->join('longbing_card_job b', 'b.id = a.job_id', 'left')
            ->field(['a.name', 'a.avatar', 'a.create_time', 'b.name as job_name'])
            ->find();

        if (!$info) {
            return $this->error('staff_in is not found');
        }

//        $info['avatar'] = $this->lb_src_trans($info['avatar'], false, $_W);

        $info['create_time'] = lb_friendly_date($info['create_time']);
        $info['article_count'] = ArticleModel::where([
            'uniacid' => $uniacid,
            'status' => 1,
            'user_id' => $to_uid,
        ])->count();

        $info['client_count'] = ArticleDateModel::where([
            'uniacid' => $uniacid,
            'status' => 1,
            'user_id' => $to_uid,
        ])->field(['sum(count) as total'])->find();

        $info['client_count'] = $info['client_count']['total'];


        $subQuery = Db::name('lb_marketing_record')
            ->where([
                'uniacid' => $uniacid,
                'type' => 1,
            ])
            ->group('article_id, user_id')
            ->buildSql();

        //  文章列表
        $data = ArticleModel::alias('a')
            ->field([
                'a.title', 'a.cover', 'a.share', 'a.update_time', 'a.share_self', 'a.share_other',
                'count(b.id) count'
            ])
            ->join("$subQuery b", 'b.article_id = a.id', 'left')
            ->order(['count' => 'desc'])
            ->where([
                'a.user_id' => $to_uid,
                'a.status' => 1,
                'a.uniacid' => $uniacid,
            ])
            ->group('a.id')
            ->paginate(20, false, ['page' => $page])
            ->toArray();

        $data['user'] = $info;

        if (isset($data['data']) && !empty($data['data']))
        {
            foreach ($data['data'] as $index => $item) {
                $data['data'][$index]['update_time2'] = lb_friendly_date($item['update_time']);
            }

        }

        return $this->success($data);
    }

    //文章排行榜--推广详情
    public function articleExtensionDetails()
    {
        global $_W;
        $uniacid = $this->_uniacid;

        $article_id = $this->_param['article_id'];
        if (!$article_id)
        {
            return $this->error('article_id is requied');
        }
        //  根据自定义的条件获取参数
        $page = $this->_param['page'] ?? 1;

        //  文章信息
        $article_info = ArticleModel::where(['id' => $article_id])
            ->field([
                'id', 'title', 'cover', 'content', 'create_time'
            ])->find();

        $article_info['create_time2'] = lb_friendly_date($article_info['create_time']);

        //  公司员工总人数
        $total_staff = UserInfo::where([
            'is_staff' => 1,
            'uniacid' => $uniacid,
            'status' => 1
        ])->count();


        //  员工推广列表
        $list = ArticleModel::alias('ar')
            ->field([
                'a.id', 'a.user_id as a_user_id', 'a.article_id',
                'a.staff_id', 'a.update_time',
                'ar.share_other', 'ar.share_self',
                'b.name', 'b.avatar',
                'count(ar.user_id) as article_count',
                'count(a.user_id) as count',
                'c.name as job_name'
            ])
            ->where([
                ['ar.content', '=', $article_info['content']],
                ['ar.user_id', '<>', 0],
                ['ar.uniacid', '=', $uniacid],
            ])
            ->join("lb_marketing_record a", 'ar.id = a.article_id && a.type = 1')
            ->join("longbing_card_user_info b", 'b.fans_id = ar.user_id','left')
            ->join("longbing_card_job c", 'c.id = b.job_id', 'left')
            ->group('staff_id')
            ->paginate(20, false, ['page' => $page])
            ->toArray();

        if (isset($list['data']) && !empty($list['data']))
        {
            foreach ($list['data'] as $index => $item) {
                $list['data'][$index]['update_time2'] = lb_friendly_date($item['update_time']);
//                $list['data'][$index]['avatar'] = $this->lb_src_trans($item['avatar'], false, $_W);
            }

        }

        $list['article_info'] = $article_info;
        $list['total_staff'] = $total_staff;
        $list['left_total'] = $list['total_staff'] - $list['total'];
        $list['left_total'] = sprintf("%.0f", $list['left_total']);

        return $this->success($list);
    }

    /**
     * @Purpose: 用户文章浏览明细
     *
     * @Param: int      $client_id
     * @Param: int      $count     查询列表类型 0 => 所有的数据 1 => 今天的数据
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function viewClientDetailed()
    {
        $uniacid = $this->_uniacid;
        //  获取当前用户id
        $uid = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;

        //  根据自定义的条件获取参数
        $client_id = $this->_param['client_id'] ?? null;
        $page = $this->_param['page'] ?? 1;
        $count = $this->_param['count'] ?? 0;

        if (!$uid || !$client_id)
        {
            return $this->error('user_id and client_id is required');
        }


        $time_start = 0;
        if ($count)
        {
            $time = date('Y-m-d');
            $time = $time . ' 00:00:00';
            $time_start = strtotime($time);
        }

        $user = User::alias('a')
            ->join('longbing_card_user b', 'a.pid = b.id', 'left')
            ->field([
                'a.nickName', 'a.avatarUrl', 'a.pid', 'a.is_qr',
                'a.is_group', 'a.type', 'a.target_id', 'a.scene',
                'a.openGId', 'b.nickName as p_nickName', 'a.create_time'
            ])
            ->where(['a.id' => $client_id])
            ->find();

        $user['source'] = '来自搜索';
        if ($user['is_qr'])
        {
            $user['source'] = '来自扫码';
        }
        if ($user['openGId'])
        {
            $user['source'] = '来自群分享';
        }
        if ($user['p_nickName'])
        {
            $user['source'] = "来自{$user['p_nickName']}的分享";
        }

        $user['create_time'] = lb_friendly_date($user['create_time']);

        $whereTotal = array(
            'user_id' => $client_id,
            'staff_id' => $uid,
            'type' => 1,
        );
        if ($time_start)
        {
            $whereTotal[] = ['create_time', '>', $time_start];
        }


        $totalRecord = ArticleRecordModel::field(['count(id) as totalCount', 'sum(length) as totalLength'])
            ->where($whereTotal)
            ->find();
        if ($totalRecord['totalLength'])
        {
            $length = $totalRecord['totalLength'];
            if ($length < 60)
            {
                $length_tmp = $length . '秒';
            } else if ($length < 3600)
            {
                $length_tmp = floor($length / 60) . '分' . $length % 60 . '秒';
            } else {
                $length_tmp = floor($length / 3600) . '小时' . floor($length % 3600 / 60) . '分' . $length % 60 . '秒';
            }
            $totalRecord['totalLength'] = $length_tmp;
        }


        $whereList = array(
            'user_id' => $client_id,
            'staff_id' => $uid,
            'type' => 1,
        );
        if ($time_start) {
            $whereList[] = ['create_time', '>', $time_start];
        }
        $subQuery = Db::name('lb_marketing_record')
            ->where($whereList)
            ->order(['id' => 'desc'])
            ->buildSql();
        $list = Db::table($subQuery . ' a')
            ->order(['a.id' => 'desc'])
            ->field(array(
                "count(a.id)" => "countId", "sum(a.length)" => "viewLength", "a.user_id",
                'b.nickName', 'b.avatarUrl', 'a.update_time', 'c.title', 'c.cover', 'c.status as article_status',
                'c.id as c_article_id'
            ))
            ->join('longbing_card_user b', 'b.id = a.user_id', 'left')
            ->join('lb_marketing_article_v2 c', 'c.id = a.article_id', 'left')
            ->group('a.article_id')
            ->paginate(20, false, ['page' => $page])
            ->toArray();

        if (isset($list['data']) && !empty($list['data'])) {
            foreach ($list['data'] as $index => $item) {
                $tmp = $item['update_time'];
                $list['data'][$index]['update_time'] = lb_friendly_date($tmp);
                $length = $item['viewLength'];
                if ($length < 60) {
                    $length_tmp = $length . '秒';
                } else if ($length < 3600) {
                    $length_tmp = floor($length / 60) . '分' . $length % 60 . '秒';
                } else {
                    $length_tmp = floor($length / 3600) . '小时' . floor($length % 3600 / 60) . '分' . $length % 60 . '秒';
                }
                $list['data'][$index]['viewLength'] = $length_tmp;
            }
        }

        $data = $list;
        $data['totalRecord'] = $totalRecord;
        $data['user'] = $user;


        return $this->success($data);

    }

    //文章详情二维码
    public function createArticleQr()
    {

        $to_uid = $this->_param['to_uid'] ?? null;
        $user_id = $this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null;
        $id = $this->_param['article_id'] ?? null;
        $uniacid = $this->_uniacid;

        $miniPath = 'article/pages/detail';
        $imagePath = "images/qr/article_qr/{$uniacid}/";

        $src = createMiniQr($to_uid, $user_id, 'article_qr', $this->_uniacid, $miniPath, $imagePath, $id, 1, 'v2');

        if ($src == '') {
            return $this->error('operation failed');
        }

        return $this->success(['src' => $src]);
    }

    /**
     * @Purpose: 检查能不能使用获客文章
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    private function checkArticle($uniacid, $card_id, $user_id)
    {
        // true 还可以创建, false达到上限
        $m_staff = new IndexUserInfo();
        if ($card_id)
        {
            $cardInfo = $m_staff->userInfo(['id' => $card_id]);
        } else {
            $cardInfo = $m_staff->where(['fans_id' => $user_id, 'uniacid' => $uniacid])->find();
        }

        if (!$cardInfo)
        {
            return false;
        }

        $cacheKey = 'article_' . $cardInfo['id'];
//        Cache::store( 'redis' )->set( $cacheKey, null );
        $cache = Cache::store('redis')->get($cacheKey);

        if ($cache === true)
        {
            return true;
        }

        if (!defined('LONGBING_AUTH_ARTICLE_SINGLE'))
        {
            return false;
        }
        if (LONGBING_AUTH_ARTICLE_SINGLE == 0)
        {
            return false;
        }


        $config = AppConfig::where([
            'uniacid' => $cardInfo['uniacid']
        ])->find();

        if (!$config)
        {
            Cache::store('redis')->set($cacheKey, false);
            return false;
        }

        if ($config['autograph'] == 0)
        {
            Cache::store('redis')->set($cacheKey, false);
            return false;
        }

        if ($config['autograph'] < $config['signature'])
        {
            Cache::store('redis')->set($cacheKey, false);
            return false;
        }


        if ($cardInfo['autograph'] == 0 || $cardInfo['signature'] == 0)
        {
            Cache::store('redis')->set($cacheKey, false);
            return false;
        }

        if ($cardInfo['signature'] > LONGBING_AUTH_ARTICLE_SINGLE)
        {
            Cache::store('redis')->set($cacheKey, false);
            return false;
        }

        $time = time();

        if ($cardInfo['autograph'] - 123456789 < $time)
        {
            Cache::store('redis')->set($cacheKey, false);
            return false;
        }
        Cache::store('redis')->set($cacheKey, true);

        return true;
    }

    private function lb_src_trans($src, $local_path = false, $_W)
    {

        if (empty($src))
        {
            return '';
        }
        if (strexists($src, "c=utility&a=wxcode&do=image&attach="))
        {
            return $src;
        }
        if (strexists($src, 'addons/'))
        {
            return $_W['siteroot'] . substr($src, strpos($src, 'addons/'));
        }
        if (strexists($src, $_W['siteroot']) && !strexists($src, '/addons/'))
        {
            $urls = parse_url($src);
            $src = $t = substr($urls['path'], strpos($urls['path'], 'images'));
        }
        $t = strtolower($src);
        if (strexists($t, 'https://mmbiz.qlogo.cn') || strexists($t, 'http://mmbiz.qpic.cn'))
        {
            $url = url('utility/wxcode/image', array('attach' => $src));
            return $_W['siteroot'] . 'web' . ltrim($url, '.');
        }
        if ((substr($t, 0, 7) == 'http://') || (substr($t, 0, 8) == 'https://') || (substr($t, 0, 2) == '//')) {
            return $src;
        }
        if ($local_path || empty($_W['setting']['remote']['type']) || file_exists(IA_ROOT . '/' . $_W['config']['upload']['attachdir'] . '/' . $src)) {
            $src = $_W['siteroot'] . $_W['config']['upload']['attachdir'] . '/' . $src;
        } else {
            $src = $_W['attachurl_remote'] . $src;
        }
        return $src;
    }

    private function setClients($to_uid, $user_id, $article_id, $record_id, $uniacid)
    {
        $recordModel = new ArticleRecordModel();
        $tmp = date('Y-m-d') . ' 00:00:00';
        $times = strtotime($tmp);
        $count = $recordModel
            ->where([
                ['article_id', '=', $article_id],
                ['user_id', '=', $user_id],
                ['staff_id', '=', $to_uid],
                ['type', '=', 1],
                ['uniacid', '=', $uniacid],
                ['id', '<', $record_id],
                ['create_time', '>', $times]
            ])
            ->count();

        if ($count) {
            return false;
        }


        $date = date('m/d');
        $year = date('Y');
        $info = ArticleDateModel::where([
            'user_id' => $to_uid,
            'uniacid' => $uniacid,
            'month_day' => $date,
            'year' => $year,
        ])
            ->find();

        if ($info) {
            $info->count += 1;
            $info->save();
        } else {
            ArticleDateModel::create([
                'user_id' => $to_uid,
                'uniacid' => $uniacid,
                'month_day' => $date,
                'year' => $year,
                'count' => 1,
            ]);
        }
        return true;
    }

    private function getDaysArr($total)
    {
        $array = array();
        for ($i = 0; $i < $total; $i++) {
            $day = $total - $i - 1;
            $date = date('m/d', strtotime("-{$day} days"));
            $array[$date] = [
                'count' => 0,
                'date' => $date
            ];
        }
        return $array;
    }
}
